package com.zhangxiaofanfan.hotcode.third;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * TODO
 *
 * @author zhangxiaofanfan
 * @date 2024-05-22 08:10:29
 */
public class HotCode006 {
    public static void main(String[] args) {

    }

    public List<List<Integer>> threeSum(int[] nums) {
        if (nums == null || nums.length < 3) {
            throw new IllegalArgumentException("nums length must be >= 3");
        }
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        int index1 = 0;
        int indexLeft = 0;
        int indexRight = 0;
        int sum = 0;
        while (index1 < nums.length - 2){
            indexLeft = index1 + 1;
            indexLeft = nums.length - 1;
            while (indexLeft < indexRight) {
                sum = nums[index1] + nums[indexLeft] + nums[indexRight];
                if (sum == 0) {
                    result.add(new ArrayList<>(List.of(nums[index1], nums[indexLeft], nums[indexRight])));
                    while (indexLeft < indexRight && nums[indexLeft++] == nums[indexLeft]);
                    while (indexLeft < indexRight && nums[indexRight--] == nums[indexRight]);
                } else if (sum < 0) {
                    while (indexLeft < indexRight && nums[indexLeft++] == nums[indexLeft]);
                } else {
                    while (indexLeft < indexRight && nums[indexRight--] == nums[indexRight]);
                }
            }
            while (nums[index1++] == nums[index1]);
        }
        return result;
    }
}
